package cz.cvut.fit.web.nakupniSeznam.ws;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;

import cz.cvut.fit.web.nakupniSeznam.Constants;
import cz.cvut.fit.web.nakupniSeznam.ws.conv.ErrorConverter;

public class Utils {

	public static String getKey(HttpHeaders hh,
			Response.ResponseBuilder builder, Logger LOG) {
		String key;
		try {
			key = hh.getRequestHeader(Constants.HEADER_USER_NAME).get(0);
			return key;
		} catch (NullPointerException ex) {
			LOG.error(Constants.WS_NO_KEY_HEADER, ex);
			builder.status(Response.Status.BAD_REQUEST);
			builder.entity(new ErrorConverter(Constants.WS_BAD_FORMAT));
			return null;
		}
	}

	public static boolean checkKeyLength(String key,
			Response.ResponseBuilder builder, Logger LOG) {
		try {
			if (key.length() != Constants.CONSTRAINT_KEY_LENGTH)
				throw new NumberFormatException();
		} catch (NumberFormatException ex) {
			builder.status(Response.Status.BAD_REQUEST);
			builder.entity(new ErrorConverter(Constants.WS_BAD_FORMAT));
			LOG.error(Constants.WS_FAILED, ex);
			return false;
		}
		return true;
	}
}
